package com.suncp.controller;

import com.suncp.entity.Books;
import com.suncp.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


/**
 * (Books)表控制层
 *
 * @author suncp
 * @since 2020-11-30 13:35:44
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService booksService;

    /**
     * 查询所有的书籍,返回到一个书籍展示页面
     */
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = booksService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }


    /**
     * 跳转到增加书籍页面
     *
     * @return
     */
    @RequestMapping("/toAddBook")
    public String toAddBookPage() {
        return "addBook";
    }

    /**
     * 添加书籍方法
     */
    @RequestMapping("/addBook")
    public String addBook(Books book) {
        System.out.println("addBook: " + book);
        booksService.addBook(book);
        return "redirect:/book/allBook";
        // 重定向到@RequestMapping("/allBook") 方法
    }

    /**
     * 跳转到修改页面  - /toUpdate?id=**
     */
    @RequestMapping("/toUpdate")
    public String toUpdateBook(@RequestParam("id") int id, Model model) {
        Books book = booksService.queryBookById(id);
        model.addAttribute("QBook", book);
        return "updateBook";
    }

    /**
     * 修改书籍
     * @param book
     * @return
     */
    @RequestMapping("/updateBook")
    public String updateBook(Books book) {
        System.out.println("要修改的书籍：" + book);
        booksService.updateBook(book);
        return "redirect:/book/allBook";
    }

    /**
     * 删除书籍
     * @param id 要删除的书籍id
     * @return
     */
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable(value = "bookId") int id){
        System.out.println("id" + id);
        booksService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    /**
     * 根据名字查询书籍
     * @param bookName 书名
     * @param model 视图解析
     * @return
     */
    @RequestMapping("/queryBookByName")
    public String queryBook(@RequestParam("queryBookName")String bookName, Model model){
        System.out.println(" 书名参数:" + bookName);
        List<Books> books = booksService.queryBookByName(bookName);
        System.err.println("queryBookByName" + books);
        model.addAttribute("list", books);
        return "/allBook";
    }

}